package com.kk.多线程之多个生产者和消费者;


/**
 * @author little_lunatic
 * @date 2023-03-02
 */
class Resource {  //生产者和消费者都要操作的资源
    private String name;
    private int count = 1;
    private boolean flag = false;

    // 生产
    public synchronized void shengchan(String name) {
        while (flag) {
            try {
//                TimeUnit.SECONDS.sleep(1);
                wait();
            } catch (Exception e) {
            }
        }
        this.name = name + "---" + count++;
        System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
        flag = true;
        this.notifyAll();
    }

    // 消费
    public synchronized void xiaofei() {
        while (!flag) {
            try {
//                TimeUnit.SECONDS.sleep(1);
                wait();
            } catch (Exception e) {
            }
        }
        System.out.println(Thread.currentThread().getName() + "...消费者..." + this.name);
        flag = false;
        this.notifyAll();
    }
}

class Producer implements Runnable {
    private Resource res;

    Producer(Resource res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            res.shengchan("商品");
        }
    }
}

class Consumer implements Runnable {
    private Resource res;

    Consumer(Resource res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            res.xiaofei();
        }
    }
}

//生产者生产一个商品，紧接着消费者消费一个商品

/**
 * @author MH
 */
public class ProducerConsumerDemo {
    public static void main(String[] args) {
        Resource r = new Resource();
        Producer pro = new Producer(r);
        Consumer con = new Consumer(r);
        Thread t1 = new Thread(pro);
        Thread t2 = new Thread(con);
        Thread t3 = new Thread(pro);
        Thread t4 = new Thread(con);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
